package admin

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"tcsc/models"
	"tcsc/sword"

	"github.com/astaxie/beego"
)

type Brand struct {
	BaseController
}

func (c *Brand) Get() {
	c.Data["column"] = models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	cid := c.GetString("cid")
	c.Data["cid"] = cid
	if cid != "" {
		var cids []string
		column := models.Query(`select id from mt_column where pid=` + cid + ` and status=1`)
		for _, v := range column {
			id := v["id"].(string)
			cids = append(cids, id)
			columnson := models.Query(`select id from mt_column where pid=` + id + ` and status=1`)
			for _, s := range columnson {
				cids = append(cids, s["id"].(string))
			}
		}
		if len(cids) > 0 {
			var w2 []string
			for _, c2 := range cids {
				w2 = append(w2, `a.cid like '%`+c2+`,%'`)
			}
			ws2 := strings.Join(w2, ` or `)
			ws2 = `(` + ws2 + `)`
			w = append(w, ws2)
		}
	}
	search := c.GetString("search")
	if search != "" {
		w = append(w, `a.name like '%`+search+`%'`)
	}
	// w = append(w, `a.gid=`+c.Gid)
	ob := ` order by a.sort desc,a.addtime desc`
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,b.name as gname,c.pathname from mt_brand a left join mt_shop b on a.gid=b.id left join mt_resources c 
	on a.logo=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_brand a where ` + ws
	info := models.Query(sql)
	for _, v := range info {
		cid2 := fmt.Sprint(v["cid"])
		cid2 = strings.Trim(cid2, ",")
		if cid2 == "" {
			cid2 = "''"
		}
		v["lm"] = models.Query(`select name from mt_column where id in (` + cid2 + `)`)
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/brand/index?`
	if c.Gid != "0" {
		c.TplName = "admin/brand/shop-index.html"
	} else {
		c.TplName = "admin/brand/index.html"
	}
}

type BrandAE struct {
	BaseController
}

func (c *BrandAE) Get() {
	column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	for _, v := range column {
		son := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + v["id"].(string))
		for _, s := range son {
			s["sonson"] = models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + s["id"].(string))
		}
		v["son"] = son
	}
	c.Data["column"] = column
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_brand a left join mt_resources b on a.logo=b.id where a.id=` + id); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/brand/index")
		}
		classify := models.Query(`select id from mt_brand_classify 
			where status = 1 and (bid like '%,` + id + `' or bid like '` + id + `,%' or bid like '%,` + id + `,%')`)
		if classify != nil {
			c.Data["classify"] = classify[0]["id"]
		}
	}
	c.Data["brand"] = models.Query(`select id,name from mt_brand where status=1 and censoring=1 and type=0`)
	brandStreet := models.Query(`select id,name from mt_brand_classify where status=1`)
	c.Data["brandStreet"] = brandStreet
	c.TplName = "admin/brand/ae.html"
}
func (c *BrandAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	input.Set("cid", strings.Replace(strings.Trim(strings.Join(c.GetStrings("cid"), ","), ","), ",,", ",", -1)+",")
	input.Set("relevance", strings.Replace(strings.Trim(strings.Join(c.GetStrings("relevance"), ","), ","), ",,", ",", -1)+",")
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	preClassify := input.Get("classifyId")
	brandClassify := input.Get("brandStreet")
	input.Del("brandStreet")
	input.Del("classifyId")
	if res, err := models.Save("mt_brand", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		id := strconv.FormatInt(res, 10)
		c.Data["json"] = 1
		models.Exec(`update mt_product set censoring=?,is_show=? where bid=?`, input.Get("censoring"), input.Get("is_show"), id)
		if preClassify != "" {
			if preClassify != brandClassify {
				prev := models.Query(`select bid from mt_brand_classify where id=?`, preClassify)
				bid := fmt.Sprint(prev[0]["bid"])
				if bid != "" {
					reg, _ := regexp.Compile(`^` + id + `,|,` + id + `$|^` + id + `$`)
					str := reg.ReplaceAllString(bid, "")
					reg2, _ := regexp.Compile(`,` + id + `,`)
					str = reg2.ReplaceAllString(str, ",")
					models.Exec(`update mt_brand_classify set bid=? where id=?`, str, preClassify)
				}
				current := models.Query(`select bid from mt_brand_classify where id=?`, brandClassify)
				bid = fmt.Sprint(current[0]["bid"])
				arr := strings.Split(bid, ",")
				arr = append(arr, id)
				bidStr := strings.Join(arr, ",")
				bidStr = strings.Trim(bidStr, ",")
				models.Exec(`update mt_brand_classify set bid=? where id=?`, bidStr, brandClassify)
			}
		} else {
			current := models.Query(`select bid from mt_brand_classify where id=?`, brandClassify)
			bid := fmt.Sprint(current[0]["bid"])
			arr := strings.Split(bid, ",")
			arr = append(arr, id)
			bidStr := strings.Join(arr, ",")
			bidStr = strings.Trim(bidStr, ",")
			models.Exec(`update mt_brand_classify set bid=? where id=?`, bidStr, brandClassify)
		}
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 34
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type BrandContent struct {
	BaseController
}

func (c *BrandContent) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname,c.name as gname from mt_brand a left join mt_resources b on a.logo=b.id left join mt_shop c on 
		a.gid=c.id where a.id=` + id); info != nil {
			for _, i := range info {
				cids := fmt.Sprint(i["cid"])
				cids = strings.Trim(cids, ",")
				if cids == "" || cids == "<nil>" {
					cids = "''"
				}
				column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0 and id in(` + cids + `)`)
				for _, v := range column {
					son := models.Query(`select id,name from mt_column where type='p' and status=1 and id in(` + cids + `) and pid=` + v["id"].(string))
					for _, s := range son {
						s["sonson"] = models.Query(`select id,name from mt_column where type='p' and id in(` + cids + `) and status=1 and pid=` + s["id"].(string))
					}
					v["son"] = son
				}
				c.Data["column"] = column
			}
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/brand/index")
		}
	} else {
		c.Ctx.Redirect(302, "/admin/brand/index")
	}
	c.TplName = "admin/brand/content.html"
}

type BrandClassify struct {
	BaseController
}

func (c *BrandClassify) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	w := ` where a.status=1`
	info := models.Query(`select a.id,a.name,a.intr,a.addtime,a.fold,b.pathname from mt_brand_classify a 
		left join mt_resources b on a.img=b.id` + w + lt)
	sql2 := `select count(a.id) as totals from mt_brand_classify a` + w
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.TplName = "admin/brand/classify.html"
}

type BrandClassifyAE struct {
	BaseController
}

func (c *BrandClassifyAE) Get() {
	id := c.GetString("id")
	member := models.Query(`select a.uid,b.monicker,b.mobile,c.name as vipName 
		from mt_member_vip_order a 
		left join mt_member b on a.uid=b.id 
		left join mt_member_vip c on a.vid=c.id 
		wwhere a.vid in (select id from mt_member_vip where gid=0 and status=1) and b.status=1 and b.censoring=1`)
	brand := models.Query(`select id,name from mt_brand where status=1 and censoring=1`)
	if id != "" {
		info := models.Query(`select a.id,a.name,a.intr,a.uid,a.bid,a.fold,a.img,b.pathname from mt_brand_classify a 
			left join mt_resources b on a.img=b.id 
			where a.id=? and a.status=1`, id)
		c.Data["info"] = info[0]
	} else {

	}
	c.Data["member"] = member
	c.Data["brand"] = brand
	c.TplName = "admin/brand/classify_ae.html"
}

func (c *BrandClassifyAE) Post() {
	input := c.Input()
	json := make(map[string]interface{})
	c.Data["json"] = &json
	defer c.ServeJSON()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	bid := strings.Replace(strings.Trim(strings.Join(c.GetStrings("bid"), ","), ","), ",,", ",", -1)
	uid := strings.Replace(strings.Trim(strings.Join(c.GetStrings("uid"), ","), ","), ",,", ",", -1)
	input.Set("bid", bid)
	input.Set("uid", uid)
	// bidArr := strings.Split(bid, ",")
	// for _, v := range bidArr {
	// 	classify := models.Query(`select * from mt_brand_classify
	// 		where bid like '`+v+`,%' or bid like '%,`+v+`' or bid like '%,`+v+`,%'`)
	// 	for _, item := range classify {
	// 		id := item["id"].(string)
	// 		bids := fmt.Sprint(item["bid"])
	// 		if bids != "" {
	// 			bidArr := strings.Split(bids, ",")
	// 			isChange := false
	// 			for index, _ := range bidArr {
	// 				if bidArr[index] == v {
	// 					beego.Debug()
	// 					bidArr = append(bidArr[:index], bidArr[index+1:])
	// 					isChange = true
	// 					continue
	// 				}
	// 			}
	// 			if isChange {
	// 				bids := strings.Join(bidArr, ",")
	// 				if err := models.Exec(`update mt_brand_classify set bid = ? where id = ?`, bids, id) {
	// 					beego.Debug(err)
	// 					json["status"] = "0"
	// 					return
	// 				}
	// 			}
	// 		}
	// 	}
	// }
	if _, err := models.Save("mt_brand_classify", input); err != nil {
		beego.Debug(err)
		json["status"] = "0"
	} else {
		json["status"] = "1"
	}
}
